# coding=utf-8

import logging

import sys
reload(sys);
sys.setdefaultencoding("utf-8")


def try_select_default(response, xpath_list):
    if isinstance(xpath_list, str):
        xpath = xpath_list;
        return select_default(response, xpath)

    if isinstance(xpath_list, list):
        for xpath in xpath_list:
            r = select_default(response, xpath)
            if r != "":
                return r
    else:
        raise ValueError("error parameter type %s..." % type(xpath_list))

    return ""


def select_default(response, xpath):
    r = ""
    elem = response.selector.xpath(xpath)
    if len(elem) > 0:
        for e in elem:
            r = e.extract().strip()
            # r = e.extract().decode('utf-8').strip()
            if r != "":
                break
        # r = elem[0].extract().decode('utf-8')

    return r


def try_select_all(response, xpath_list):
    if isinstance(xpath_list, str):
        xpath = xpath_list;
        return select_all(response, xpath)

    if isinstance(xpath_list, list):
        for xpath in xpath_list:
            r = select_all(response, xpath)
            if r != "":
                return r
    else:
        raise ValueError("error parameter type %s..." % type(xpath_list))

    return ""


def select_all(response, xpath):
    elem = response.selector.xpath(xpath)
    if len(elem) > 0:
        lst = [e.extract().decode('utf-8').strip() for e in elem]
        return lst
    else:
        return []


def configure_logging(logger):
    stdout_handler = logging.StreamHandler(sys.stdout)
    logger.addHandler(stdout_handler)